<?php

namespace App\Http\Controllers;

use App\Http\Controllers\BaseController;
use App\Models\CategoryModel;
use App\Models\EveryModel;
use App\Repositories\CategoryRepository;
use App\Repositories\EveryRepository;
use App\Repositories\MoneyLogRepository;
use Illuminate\Http\Request;

class CategoryController extends BaseController
{
    /**
     * @param Request $request
     * @param MoneyLogRepository $moneyRepository
     * @return \Illuminate\Http\JsonResponse
     */
    public function list (Request $request, CategoryRepository $categoryRepository)
    {
        $params = $request->all();
        $list = @$categoryRepository->getList($params);
//        var_dump($list);
        $list['list'] = self::buildCategoryTree($list['list']);
        return $this->success($list);
    }


    protected function buildCategoryTree($categories, $parentId = 0) {
        $branch = [];

        foreach ($categories as $category) {
            if ($category['pid'] == $parentId) {
                $children = self::buildCategoryTree($categories, $category['id']);
                if ($children) {
                    $category['children'] = $children;
                }
                $branch[] = $category;
            }
        }

        return $branch;
    }

    public function getCategoryDetail (Request $request) {
        $id = $request->input('id');
        $money = @CategoryModel::query()->find($id);
        return $this->success($money);
    }

    /**
     * @param Request $request
     * @param MoneyLogRepository $moneyRepository
     * @return \Illuminate\Http\JsonResponse
     */
    public function save (Request $request, CategoryRepository $categoryRepository)
    {
        $allParams = $request->all();
        $rst = @$categoryRepository->save($allParams);
        if ($rst) {
            return $this->success([]);
        }
        return $this->error(405, '保存失败，请稍后再试');
    }

    public function getParentCategory (CategoryRepository $categoryRepository)
    {
       $category =  $categoryRepository->getParentCategory();
       return $this->success($category);
    }
}
